package com.scriptback.service.Impl;

import com.scriptback.dto.script.ScriptUpdateRequestDTO;
import com.scriptback.entity.Scripts;
import com.scriptback.repository.ScriptRepository;
import com.scriptback.service.ScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


/**
 * 脚本服务实现类
 */
@Service
public class ScriptServiceImpl implements ScriptService {

    @Autowired
    private ScriptRepository scriptRepository;

    /**
     * 创建新脚本
     */
    @Override
    public Scripts createScript(String projectId, String name, String description, String code) {
        return scriptRepository.save(new Scripts(projectId, name, code,description ));
    }

    /**
     * 分页获取所有脚本
     */
    @Override
    public Page<Scripts> getAllScripts(Pageable pageable) {
        return scriptRepository.findAll(pageable);
    }

    /**
     * 分页获取指定项目下的脚本
     */
    @Override
    public Page<Scripts> getScriptsByProjectId(String projectId, Pageable pageable) {
        return scriptRepository.findAllScriptByProjectId(projectId, pageable);
    }

    /**
     * 按名称搜索脚本
     */
    @Override
    public Page<Scripts> searchScriptsByName(String name, Pageable pageable) {
        return scriptRepository.findSciptsByScriptName(name, pageable);
    }

    /**
     * 在指定项目中按名称搜索脚本
     */
    @Override
    public Page<Scripts> searchScriptsByNameInProject(String projectId, String name, Pageable pageable) {
        return scriptRepository.findSciptsByProjectIdAndSciptName(pageable,projectId,name);
    }

    /**
     * 根据ID获取脚本
     */
    @Override
    public Scripts getScriptById(String id) {
        return scriptRepository.findById(id).orElseThrow(() -> new RuntimeException("脚本通过Id查询异常"));
    }

    /**
     * 更新脚本信息
     */
    @Override
    public Scripts updateScript(String id, ScriptUpdateRequestDTO updateRequest) {
        Scripts script = getScriptById(id);
        script.setName(updateRequest.getScript_name());
        script.setDescription(updateRequest.getScript_description());
        script.setCode(updateRequest.getScript_code());
        return scriptRepository.save(script);
    }

    /**
     * 删除脚本
     */
    @Override
    public void deleteScript(String id) {
        scriptRepository.deleteById(id);
    }
}
